package com.wl.application.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wl.application.common.all.Const;
import com.wl.application.common.all.Result;
import com.wl.application.common.all.ResultEnum;
import com.wl.application.common.childException.UserException;
import com.wl.application.entity.User;
import com.wl.application.services.AllotService;
import com.wl.application.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author wl
 * @version 1.0
 * @date 2022/6/21
 * @description:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AllotService allotService;


    /**
     * 分页获取所有的user数据
     */

    @PostMapping("/page")
    public Result page(@RequestBody Page<User> page){
        Page<User> page1 = userService.page(page);
        return Result.ok((page1));
    }
    @PutMapping("/updateState/{id}")
    public Result updateState(@PathVariable("id") Integer id){
        User byId = userService.getById(id);

        if(byId.getUstate().equals(Const.NO_ACTIVATE)){
            byId.setUstate(Const.ACTIVATE);
        }else{
            byId.setUstate(Const.NO_ACTIVATE);
        }
        return Result.ok(userService.updateById(byId));
    }

    @PostMapping("/save/{rid}")
    public Result save(@RequestBody User user,@PathVariable("rid")Integer rid){
        user.setCreateTime(new Date());
        //注册的用户默认为不冻结
        user.setUstate(Const.ACTIVATE);
        boolean save = userService.save(user);
        //为新增的用户添加默认权限 mybatis plus会自动的主键回填
        allotService.addRoleToUser(rid, Arrays.asList(new Integer[]{user.getId()}));
        return Result.ok("添加成功!",save);
    }
    @DeleteMapping("/del")
    public Result del(@RequestBody List<Integer> ids) {
        allotService.removeUserAndUr(ids);
        boolean b = userService.removeBatchByIds(ids);
        return Result.ok("删除成功!");
    }
    @GetMapping("/one/{id}")
    public Result getOne(@PathVariable("id") Integer id){
        User byId = userService.getById(id);
        return  Result.ok(byId);
    }
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        boolean b = userService.updateById(user);
        return Result.ok("修改成功!");
    }

    @PostMapping("/checkName/{name}")
    public Result checkName(@PathVariable("name") String name){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("uname",name);
        User one = userService.getOne(wrapper);
        if (one == null) {
            return Result.ok("");
        }
        return Result.ok(ResultEnum.NAME_HAVE.getMsg());
    }
}
